layui.use(['table', 'form', 'element'], function () {
    let table = layui.table,
        form = layui.form,
        $ = layui.jquery,
        element = layui.element;
    //方法级渲染
    table.render({
        elem: '#admRegistryTagHst'
        , url: '/admRegistryTagHst/page'
        , toolbar: '#toolbarTable'
        , title: 'docker下载'
        , totalRow: true
        ,skin: 'line'
        , id: "admRegistryTagHst"
        , cols: [[
            {checkbox: true, fixed: true}
            , {field: 'projectName', title: '项目名称', width: 250, sort: true}
            , {field: 'namespaceName', title: '命名空间', width: 250, sort: true}
            , {field: 'registryName', title: '仓库名称', width: 250, sort: true}
            , {field: 'imageName', title: '镜像名称', width: 250, sort: true}
            , {field: 'tag', title: '版本', width: 250, sort: true}
            , {field: 'updateTime', title: '更新时间', width: 250, sort: true}
        ]]
        , even: true
        , page: true //是否显示分页
        , skip: true //开启跳页
        , limits: [10, 30, 60]
        , width: 1700
        // , height: 'full-150'
        , limit: 10 //每页默认显示的数量
        , parseData: function (res) { //res 即为原始返回的数据
            var data = res.data;
            return {
                "code": status, //解析接口状态   （好像必须是0 才可以）
                "msg": data.desc, //解析提示文本
                "count": data.total, //解析数据长度
                "data": data.records //解析数据列表
            };
        }
        , done: function (res, currentCount) {
            //***重点***：table渲染完成后渲染element进度条
            element.render()
        }

    });

    //头工具栏事件
    table.on('toolbar(admRegistryTagHst)', function (obj) {
        let data = table.checkStatus(obj.config.id).data;
        let ids;
        switch (obj.event) {
            case "exportImages":
                ids = check(data);
                if (!ids){
                    return;
                }
                exportImages(ids);
                break;
            case "deployProduction":
                ids = check(data);
                if (!ids){
                    return;
                }
                deployProduction(ids);
                break;
        }
        ;
    });
    function deployProduction(ids){
        var loading = layer.msg('正在部署生产ing', { icon: 16, shade: [0.5, '#fff'], time: 0 });
        $.ajax({
            type: "GET",//方法类型
            dataType: "json",//预期服务器返回的数据类型
            url: "/admRegistryTagHst/deployProduction?ids=" + ids,//url
            success: function (result) {
                setTimeout(function() {
                    layer.close(loading);
                    // 处理返回结果
                    // ...
                }, 30000); // 延迟30秒，即30000毫秒
            },
            error: function () {
                layer.close(loading);
                alert("异常！");
            }
        });
    }
    function exportImages(ids) {
        layer.load()
        const  url = '/admRegistryTagHst/exportImages/';
        const  data = {
            ids:ids,
        };
        const form = $('<form></form>');
        form.attr('action', url + "?rand=" + Math.random());
        form.attr('method', 'get');
        for (const item in data) {
            const input = $('<input type="text" />');
            input.attr('name', item);
            input.attr('value', data[item]);
            form.append(input);
        }
        form.appendTo('body').submit().remove();
    }

    function check(data) {
        if (data.length == 0) {
            layer.msg("请先勾选数据", {icon: 2, time: 3000});
            return;
        }
        let ids = "";
        for (let i = 0; i < data.length; i++) {
            ids += data[i].id + ","
        }
        ids = ids.substr(0, ids.length - 1);
        return ids;
    }


    $('#query').click(function () {
        search();
    });
    $(document).keyup(function (event) {
        if (event.keyCode == 13) {
            search();
        }
    });

    function search() {
        //执行重载
        table.reloadData('admRegistryTagHst', {
            method: 'get',
            page: {
                curr: 1 //重新从第 1 页开始
            }
            , where: {
                projectId: $('#projectId').val(),
                namespaceId: $('#namespaceId').val(),
                content: $('#content').val(),
                tag: $('#tag').val(),
            }
        }, 'data');
    }


    $(function () {
        getProject("")
        getNamespace("")
        setTimeout(function() {
            search();
        },10)

    })
    projectNameInput = function (e) {
        const val = $("#projectName").val();
        getProject(val)
    }
    let projectData

    function getProject(projectName) {
        $.ajax({
            type: "GET",//方法类型
            dataType: "json",//预期服务器返回的数据类型
            url: "/admProject/getAll?name=" + projectName,//url
            success: function (result) {
                projectData = result
                $("#projectId").html("");
                var html = "";
                $("#projectId").html("<option value=\"\">请选择项目</option>");
                if (result != null) {
                    $.each(result, function (index, item) {
                        html += "<option  value='" + item.id + "'>" + item.projectName + "</option>";
                    })
                }
                $("#projectId").append(html);
                form.render('select');
                if (projectName != null && projectName != '') {
                    $(".projectId").find(".layui-form-select").addClass("layui-form-selected")
                }
            },
            error: function () {
                alert("异常！");
            }
        });
    }

    // 监听下拉框改变事件,修改输入框中的内容
    form.on("select(projectId)", function (data) {
        let value = data.value
        let selectObj = projectData.filter(item => {
            return item.id == value
        })
        $("#projectName").val(selectObj[0].projectName);
    })


    namespaceNameInput = function (e) {
        const val = $("#namespaceName").val();
        getNamespace(val)
    }
    let namespaceData

    function getNamespace(name) {
        $.ajax({
            type: "GET",//方法类型
            dataType: "json",//预期服务器返回的数据类型
            url: "/admNamespace/getAll?name=" + name,//url
            success: function (result) {
                namespaceData = result
                $("#namespaceId").html("");
                var html = "";
                $("#namespaceId").html("<option value=\"\">请选择命名空间</option>");
                if (result != null) {
                    $.each(result, function (index, item) {
                        html += "<option  value='" + item.id + "'>" + item.name + "</option>";
                    })
                }
                $("#namespaceId").append(html);
                form.render('select');
                if (name != null && name != '') {
                    $(".namespaceId").find(".layui-form-select").addClass("layui-form-selected")
                }
            },
            error: function () {
                alert("异常！");
            }
        });
    }

    // 监听下拉框改变事件,修改输入框中的内容
    form.on("select(namespaceId)", function (data) {
        let value = data.value
        let selectObj = namespaceData.filter(item => {
            return item.id == value
        })
        $("#namespaceName").val(selectObj[0].name);
    })


});
